<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/11
 * Time: 9:11
 */

namespace App\HttpController\V1;

use alipay\AppPay;
use App\Common\Checking;
use wechatpay\WxApp;
use App\HttpController\Taoran\Functions\Publics;
class Orders extends Auth
{
    protected $values;
    protected $appid='wx08e600eb7ad66cd1';
    protected $mchid='1527074921';
    protected $key='tv0ov06vgvavh1ml5enx9dgocetsvbyg';//自己设置的微信商家key
    /**
     * 下单页面
     */
    function create_order(){

        $param=$this->input('id,type');//商品id 数量  type=1直接下单   type=2购物车下单
        $level=$this->db->where('id',$this->user->id)->getValue('users','level');
        $address=$this->db->where('user_id',$this->user->id)->where('is_default',2)->getOne('address','*');
        if(in_array($level,[2,3])) {
            $price='vip_price';
        }else{
            $price='market_price';
        }
        $info=[];
        $money=0;
        if($param['type']==1){
            $goods_info=$this->db->where('id',$param['id'])->getOne('goods',"id,$price as price,goods_name,goods_pic");
            $goods_info['goods_pic']=QINIU_URL.$goods_info['goods_pic'];
            $info[]=$goods_info;
            $money=$goods_info['price'];
        }elseif ($param['type']==2){
            $car_id=explode(",",$param['id']);
            $shop_car=$this->db->whereIn('id',$car_id)->get('shop_car');
            foreach ($shop_car as $k=>&$v){
                $goods_info=$this->db->where('id',$v['goods_id'])->getOne('goods',"id,$price as price,goods_name,goods_pic");
                $goods_info['goods_pic']=QINIU_URL.$goods_info['goods_pic'];
                $goods_info['num']=$v['num'];
                $info[]=$goods_info;
                $money+=$goods_info['price']*$goods_info['num'];
            }
        }else{
            return $this->writeJson(-202,null,'类型错误');
        }
        if(!$info||$info==[]){
            return $this->writeJson(-203,null,'商品不存在');
        }
        return $this->writeJson(200,['list'=>$info,'money'=>$money,'address'=>$address],'获取成功');
    }

    /**
     * 取消订单
     */
    function del_order(){
        $id=$this->input('id');
        try{
            $this->db->where('id',$id)->update('orders',['status'=>2]);
            return $this->writeJson(200,null,'成功');
        }catch (\Exception $e){
            return $this->writeJson($e->getCode(),null,$e->getMessage());
        }
    }

    /**
     * 确认收货
     * @return bool
     */
    function confirm_receipt(){
        $id=$this->input('id');
        try{
            $this->db->where('id',$id)->update('orders',['status'=>5]);
            return $this->writeJson(200,null,'成功');
        }catch (\Exception $e){
            return $this->writeJson($e->getCode(),null,$e->getMessage());
        }
    }

    /**
     * 创建订单
     */
    function do_create_order(){
        $param=$this->input('id,num,address_id,type');//商品id 数量   type=1直接下单   type=2购物车下单
        if ( !Checking::keyIsExistence( ['id','address_id'], $param ) ) {
            return $this->writeJson( -202, null, Checking::MESSAGE['keyIsExistence'] );
        }
        $level=$this->db->where('id',$this->user->id)->getValue('users','level');
        if(in_array($level,[2,3])) {
            $price='vip_price';
        }else{
            $price='market_price';
        }
        $money=0;
        $info=[];
        $shop_car_id=false;
        if($param['type']==1){
            $goods_info=$this->db->where('id',$param['id'])->getOne('goods',"id as goods_id,$price as goods_price,goods_name,goods_pic");
            if(!$goods_info){
                return $this->writeJson(-203,null,'商品不存在');
            }
            $goods_info['num']=$param['num'];
            $info=$goods_info;
            $money=$goods_info['goods_price']*$param['num'];
        }elseif ($param['type']==2){
            $shop_car_id=$param['id'];
            $car_id=explode(",",$param['id']);
            $shop_car=$this->db->whereIn('id',$car_id)->get('shop_car');
            foreach ($shop_car as $k=>&$v){
                $goods_info=$this->db->where('id',$v['goods_id'])->getOne('goods',"id as goods_id,$price as goods_price,goods_name,goods_pic");
                $goods_info['num']=$v['num'];
                $info[]=$goods_info;
                $money+=$goods_info['goods_price']*$goods_info['num'];
            }
        }else{
            return $this->writeJson(-202,null,'类型错误');
        }
        $order_num=Checking::ordeSnByUnique('order_num',$this->db,'orders');
        $address=$this->db->where('id',$param['address_id'])->getOne('address','province,city,area,address,phone,name');
        $this->db->startTransaction();
        try{
            $order_id=$this->db->insert('orders',[
                'order_num'=>$order_num,
                'user_id'=>$this->user->id,
                'status'=>1,
                'total_money'=>$money,
                'names'=>$address['name'],
                'phone'=>$address['phone'],
                'address'=>$address['address'],
                'province'=>$address['province'],
                'city'=>$address['city'],
                'area'=>$address['area'],
                'shop_car_id'=>$shop_car_id?$shop_car_id:null,
                'createtime'=>date('Y-m-d H:i:s'),
            ]);


            if($param['type']==1){
                $info['order_id']=$order_id;
                $info['createtime']=date('YmdHis');
                $this->db->insert('orderinfo',$info);
            }else{
                $arr=[
                    'order_id'=>$order_id,
                    'createtime'=>date('YmdHis')
                ];
                array_walk($info, function (&$value, $key, $arr) {
                    $value = array_merge($value, $arr);
                }, $arr);
                $this->db->insertMulti('orderinfo',$info);
            }
            $this->db->commit();
            return $this->writeJson(200,$order_id,'成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->writeJson(-201,null,$e->getMessage());
        }
    }


    /**
     * 订单支付
     * @return bool
     */
    function order_pay(){
        $publics = new Publics();
        $param=$this->input('order_id,pay_style,pay_password');//订单id  支付方式:1=支付宝,2=微信,3=奖学金
        if ( !Checking::keyIsExistence( ['order_id','pay_style'], $param ) ) {
            return $this->writeJson( -202, null, Checking::MESSAGE['keyIsExistence'] );
        }
        $info=$this->db->where('id',$param['order_id'])->getOne('orders');
        $goods_id=$this->db->where('order_id',$param['order_id'])->getValue('orderinfo','goods_id');
//        $info['total_money']=0.01;
        if($param['pay_style']==1){
            $notify_url=API_URL.'/v1/notify/ali_order';//异步地址
            $AliPay=new AppPay();
            $data=$AliPay->app_pay('明心堂-购买商品',$info['order_num'],$info['total_money'],$notify_url);
            return $this->writeJson(200,$data,'成功');
        }elseif ($param['pay_style']==2){
            $notify_url=API_URL.'/v1/notify/wx_order';
            $WxApp=new WxApp();
            $data=$WxApp->getPrePayOrder('明心堂-购买商品',$info['order_num'],$info['total_money'],$notify_url,$this->request()->getHeaders()['real-ip'][0]);
            return $this->writeJson(200,$data,'成功');
        }elseif($param['pay_style']==3){
            $user_info=$this->db->where('id',$this->user->id)->getOne('users','balance,pay_password');
            if(!Checking::checkPassword($user_info['pay_password'],$param['pay_password'])){
                return $this->writeJson(-205,null,'交易密码错误');
            }
            if($info['total_money']>$user_info['balance']){
                return $this->writeJson(-203,null,'余额不足');
            }
            $this->db->startTransaction();
            try{
                //记录入库
                $this->db->where('id',$this->user->id)->setDec('users','balance',$info['total_money']);
                $this->db->where('id',$param['order_id'])->update('orders',['payment_time'=>date('Y-m-d H:i:s'),'pay_style'=>$param['pay_style'],'status'=>3]);
                $this->db->insert('users_account_log',[
                    'user_id'=>$this->user->id,
                    'type'=>6,
                    'class'=>2,
                    'coin_type'=>'study',
                    'money'=>$info['total_money'],
                    'remark'=>'购买商品',
                    'createtime'=>date('YmdHis'),
                    'before_money'=>$user_info['balance']
                ]);

                $insert=$publics->call_inspiration($this->user->id,$info['total_money'],2,$this->db,$goods_id);
                $group=$publics->group($this->user->id,$info['total_money'],2,$this->db);
                if(!$insert||!$group){
                    $this->db->rollback();
                    return $this->writeJson(-202,null,'支付失败');
                }
                if($info['shop_car_id']){
                    $car_id=explode(",",$info['shop_car_id']);
                    $this->db->whereIn('id',$car_id)->delete('shop_car');
                }
                $this->db->commit();
                return $this->writeJson(200,null,'成功');
            }catch (\Exception $e){
                $this->db->rollback();
                return $this->writeJson(-201,null,$e->getMessage());
            }

        }else{
            return $this->writeJson(-204,null,'错误的支付方式');
        }
    }




}